import axios from 'axios'
import { Message, Loading } from 'element-ui'
import store from '../store/index'
import router from '../router/index'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})
const time = 3000000
let loading
// request interceptor
service.interceptors.request.use((config) => {
  const token = store.state.user.token
  loading = Loading.service({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  if (token) {
    config.headers.Authorization = 'Bearer ' + token
    const curtime = Date.now()
    const logintime = localStorage.getItem('logintime')
    // 判断时间戳的差值
    if ((curtime - logintime) > time) {
      store.dispatch('user/logout')
      router.push('/login')
      return
    }
  }

  return config
})

// response interceptor
service.interceptors.response.use((res) => {
  loading.close()
  const { data, success, message } = res.data
  if (success) {
    console.log('数据请求成功')
    if (res.config.method !== 'get' && res.config.url !== '/api/sys/profile') { Message.success(message) }
    return data
  } else {
    console.log('数据请求失败')
    Message.error(message)
    // new Error 是原生JS的方法
    return Promise.reject(new Error(message))
  }
}, err => {
  loading.close()
  // Message.error(err.message)
  // Promise.reject(err)时原生JS的一个方法,会返回一个错误对象
  if (err.response.data.code === 10002) {
    store.dispatch('user/logout')
    router.push('/login')
    Message.error('token过期')
  }
  return Promise.reject(err)
}

)

export default service
